import type { Effect, Reducer } from 'umi';

import { queryQuotaData, saveQuotaData } from '@/services/service';

export type CurrentQuota = {
  quota?: any[];
};

export type QuotaModelState = {
  currentQuota?: any[];
};

export type QuotaModelType = {
  namespace: 'quota';
  state: QuotaModelState;
  effects: {
    fetchCurrent: Effect;
    fetchSaveEditRowData: Effect;
  };
  reducers: {
    saveCurrentQuota: Reducer;
  };
};

const QuotaModel: QuotaModelType = {
  namespace: 'quota',

  state: {
    currentQuota: [],
  },

  effects: {
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryQuotaData);
      yield put({
        type: 'saveCurrentQuota',
        payload: response.quotaData,
      });
    },
    *fetchSaveEditRowData({ payload }, { call }) {
      yield call(saveQuotaData, payload);
    },
  },

  reducers: {
    saveCurrentQuota(state, action) {
      return {
        ...state,
        currentQuota: action.payload || {},
      };
    },
  },
};

export default QuotaModel;
